package com.waner.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waner.reggie.common.BaseContext;
import com.waner.reggie.common.CustomException;
import com.waner.reggie.common.R;
import com.waner.reggie.dto.OrdersDto;
import com.waner.reggie.entity.*;
import com.waner.reggie.mapper.OrdersMapper;
import com.waner.reggie.service.*;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.jni.Address;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 根据订单号和实践进行分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Page<Orders> pageWithNumberTime(@Param("page") int page,@Param("pageSize") int pageSize, @Param("number") String number, @Param("beginTime")LocalDateTime beginTime, @Param("endTime")LocalDateTime endTime) {

        // 构造条件查询器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(number), Orders::getNumber,number);
        queryWrapper.between(beginTime != null && endTime != null,Orders::getOrderTime,beginTime,endTime);
        queryWrapper.orderByAsc(Orders::getNumber);

        // 构造分页查询器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        this.page(pageInfo,queryWrapper);

        return pageInfo;
    }

    /**
     * 插入一条订单的数据
     * 插入订单对应的订单详情
     * @param order
     */
    @Override
    public void saveWithDetailAndSCart(Orders order) {
        // 获得当前用户的数据
        order.setUserId(BaseContext.getCurrentId());

        // 订单的基本信息
        order.setStatus(2); // 设置状态为待派送
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());

        // 订单的地址簿信息
        User user = userService.getById(BaseContext.getCurrentId());
        AddressBook address = addressBookService.getById(order.getAddressBookId());

        if(address == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        // 订单用户的信息
        order.setUserName(user.getName());
        order.setPhone(user.getPhone());

        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());

        long orderId = IdWorker.getId();  // 订单号的生成
        order.setNumber(String.valueOf(orderId));

        // 从购物车中提取信息，将order_detail补全（比起shopping_cart，多了一个order_id）
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        if(list == null || list.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }

        // 计算总价格
        AtomicInteger amount = new AtomicInteger(0);

        // 向订单详情中插入多条数据
        List<OrderDetail> orderDetails = list.stream().map((item)->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item,orderDetail,"id");
            orderDetail.setOrderId(orderId);
            amount.getAndAdd(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetails);

        order.setAmount(BigDecimal.valueOf(amount.get()));
        // 向订单表中插入一条数据
        this.save(order);

        // 删除购物车中菜品
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper);
    }

    @Override
    public Page<OrdersDto> pageWithDetais(int page, int pageSize) {
        // 构造分页查询器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> pageRes = new Page<>();
        // 构造条件查询器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId())
                .orderByDesc(Orders::getOrderTime);
        // 开始进行查询
        this.page(pageInfo,queryWrapper);

        // 开始进行转换，根据oderId查询orderDetail,并且封装为OrderDto进行收集
        List<Orders> ordersList = pageInfo.getRecords();
        List<OrdersDto> ordersDtos = ordersList.stream().map((order)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order,ordersDto);

            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId,order.getNumber());
            ordersDto.setOrderDetails(orderDetailService.list(wrapper));
            return ordersDto;
        }).collect(Collectors.toList());

        BeanUtils.copyProperties(pageInfo,pageRes,"records");
        pageRes.setRecords(ordersDtos);

        return pageRes;
    }
}
